package cn.xianyang.controller;

import cn.xianyang.domain.Movie;
import cn.xianyang.server.IMovieServer;
import cn.xianyang.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    private IMovieServer movieServer;

    @GetMapping
    public AjaxResult findAll() {
        //查询所有的票 并返回result
        List<Movie> movies = movieServer.findAll();
        return new AjaxResult(true,"查询成功",movies);
    }

    @PostMapping("/buyTickets")
    //买票接口 参数只有两个 不想写Dto 直接用map接收
    public AjaxResult buyTickets(@RequestBody Map map){
        //获取两个参数
        Long number =Long.parseLong(map.get("number").toString());
        Long id =Long.parseLong(map.get("id").toString());
        //进入买票业务
        return  movieServer.buyTickets(number, id);
    }

    @GetMapping("/{id}")
    //查询单个电影票
    public Movie findById(@PathVariable("id")Long id) {
        return movieServer.findById(id);
    }

    @PostMapping("/watch/{id}")
    //观看电影接口
    public AjaxResult watch(@PathVariable("id")Long id){
        //获取观看的电影 对时间进行判断是否下架或未上映
        Movie movie = movieServer.findById(id);
        Date now =new Date();
        if(now.before(movie.getEnd_time())&&now.after(movie.getStart_time())){
            return new AjaxResult(true,"可以观看本电影",null);
        }else {
            return new AjaxResult(false,"当前电影不可观看",null);
        }
    }
    @GetMapping("/findMaxTicket")
    //查询最多余票 用于注册赠送
    public Movie findMaxTicket(){
        Movie movie = movieServer.findMaxTicket();
        //直接调用买票接口减少一张余票用于赠送
        movieServer.buyTickets(1L,movie.getId());
        return movie;
    }
}
